// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// f [author] rhyme_lph
// v [email]  rhymelph@gmail.com
// T [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/bank_detail_record_item_entity.dart';
import 'package:finance_app/src/entities/bank_reconciliation_entity.dart';
import 'package:finance_app/src/entities/bank_reconciliation_record_entity.dart';
import 'package:finance_app/src/http_service/http_bank_reconciliations_service.dart';
import 'package:finance_app/src/provider/all_reports/bank_reconciliation/bank_reconciliation_provider.dart';
import 'package:finance_app/src/provider/all_reports/bank_reconciliation/views/reconcile_account_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/bank_match_transaction_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/list_select_bottom_sheet.dart';
import 'package:flutter/material.dart';

class BankReconciliationDetailWithFileProvider
    extends BaseProvider<List<BankReconciliationRecordEntity>> {
  String showStatus = 'All';
  int id;

  String title;

  BankReconciliationEntity bank;
  String closingDate;

  bool get canReconcile {
    num difference = num.parse(realDifference);
    return CashUtils.formatCashAmount(difference) == '0.00';
  }

  List<BankReconciliationRecordEntity> get filterList {
    if (showStatus == 'All') return data;
    if (showStatus == 'Unmatched')
      return List.from(
          data.where((element) => element.status == 'open').toList());
    else
      return List.from(
          data.where((element) => element.status != 'open').toList());
  }

  String realDifference;

  @override
  Future get dataFuture => HttpBankReconciliationsService.bankRecord(id);

  void onChangeStatus() {
    obtainContext?.call((context) async {
      final result =
          await showBankRecordsSelectBottomSheet(context, showStatus);
      if (result != null && showStatus != result) {
        showStatus = result;
        update();
      }
    });
  }

  void onRequestRefresh() {
    post(dataFuture,
        autoHandler: AutoHandler.Toast,
        loadingTip: S.current.loading, onSuccess: (result) async {
      await loadCheck();
      data = getEntityFromResult<List<BankReconciliationRecordEntity>>(result);
      update();
    });
  }

  void onDetail(BankReconciliationRecordEntity value) async {
    if (value.status == 'closed') {
      List<BankDetailRecordItemEntity> recordList;
      await post(
          HttpBankReconciliationsService.paymentRecord(id, value.id, 'Matched'),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        recordList =
            getEntityFromResult<List<BankDetailRecordItemEntity>>(result);
      });
      obtainContext?.call((context) async {
        bool isUnmatch = false;
        recordList.removeWhere(
            (element) => element.bankReconciliationRecordId != value.id);
        await showBankMatchTransactionBottomSheet(context, value, recordList,
            () {
          isUnmatch = true;
          Navigator.pop(context);
        });

        if (isUnmatch == true) {
          bool isSuccess = false;
          await post(HttpBankReconciliationsService.match(value.id, []),
              autoHandler: AutoHandler.Toast,
              loadingTip: S.current.loading, onSuccess: (result) {
            isSuccess = true;
          });
          if (isSuccess == true) {
            onRequestRefresh();
          }
        }
      });
    } else {
      Routes.navigateTo(RouterGenProviders.reconcileAccountRecordDetailPage,
          params: {
            'title': title,
            'bank': value,
            'bankId': id,
          });
    }
  }

  Future<void> loadCheck() async {
    BankReconciliationEntity orderEntity;
    await post(HttpBankReconciliationsService.checkBank(),
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      //如果有未完成的，自动跳转到对比页面
      orderEntity = getEntityFromResult<BankReconciliationEntity>(result);
      realDifference = orderEntity.difference;
    });
  }

  void onReconcile() async {
    await Routes.navigateTo(RouterGenProviders.reconcileAccountConfirmPage,
        params: {
          'title': title,
          'records': data,
          'reconcileId': id,
          'closingDate': closingDate,
          'beginningBalance': bank.beginningBalance,
          'statementBalance': bank.statementBalance,
        });
    if (Providers.get<BankReconciliationProvider>(
                RouterGenProviders.bankReconciliationPage, null)
            ?.getChildProvider<ReconcileAccountProvider>()
            ?.isDestroy ==
        true) {
      obtainContext?.call((context) {
        Navigator.of(context).pop();
      });
    }
  }
}
